import { Controller } from 'egg';

export default class UserController extends Controller {
  async login() {
    const { ctx } = this;
    const { username, password } = ctx.request.body;
    if (!(username && password)) {
      ctx.body = { status: -1, message: '请输入账号密码' };
      return;
    }
    const userInfo = await this.app.mysql.get('administor', { user_name: username });
    if (!userInfo) {
      ctx.body = { status: -2, message: '用户不存在' };
      return;
    }
    if (userInfo.password === password) {
      ctx.session.userInfo = userInfo;
      ctx.body = { status: 0, message: { username: userInfo.username } };
      return;
    } else {
      ctx.body = { status: 1, message: '密码错误' }
    }

  }

  async list() {
    const page = this.ctx.request.queries.page || 1;
    const data = await this.app.mysql.select('users', {
      where: { del_flag: 0 },
      orders: [['id','desc']], 
      limit: 20,
      offset: (+page - 1) * 20
    });
    const total = await this.app.mysql.count('users', { del_flag: 0 });
    this.ctx.body = { data, total: Math.ceil(total / 20) };
  }
  async create() {
    const data: any = {};
    const body = this.ctx.request.body;
    if (body.id) data.id = body.id;
    if (body.phone) data.phone = body.phone;
    if (body.nick_name) data.nick_name = body.nick_name;
    if (body.passwd) data.passwd = body.passwd;
    if (body.level) data.level = body.level;
    if (body.introduction) data.introduction = body.introduction;
    if (body.balance) data.balance = body.balance;
    if (body.gender) data.gender = body.gender;
    try {
      if (!body.id)
        await this.app.mysql.insert('users', data);
      else
        await this.app.mysql.update('users', data);
      this.ctx.body = { status: 0 }
    } catch (e) {
      this.ctx.body = { status: -1, message: e }
    }
  }

  async delete() {
    const { id } = this.ctx.params;
    try {
      await this.app.mysql.update('users', { id, del_flag: 1 });
      this.ctx.body = { status: 0 };
    } catch (e) {
      this.ctx.body = { status: -1, message: e };
    }
  }
}
